package amount_cache

import (
	"goTestToMod/redis_cache/uitility/redisdb"
	"strconv"
	"sync"
)

var once sync.Once
var amountCache *AmountCache

func GetAmountCacheInstance () *AmountCache {
	once.Do(func() {
		amountCache = &AmountCache{}
		amountCache.Timeout = 30
	})
	return amountCache
}

type AmountCache struct {
	Timeout int
}

func (c *AmountCache) GetCacheByIds (testsuitIds []string) (map[string]int, []string, error) {
	/*
		入参：testsuitIds　测试套id列表
		返回值：
			1.　已缓存的直接收集
			2.　未缓存的测试套列表
			3.	异常
	*/
	testsuitRecordMap := map[string]int{}
	noCacheTestSuitIds := []string{}
	for _, v := range testsuitIds {
		val, err := redisdb.GetCacheById(v)
		if err != nil {
			return nil, nil, err
		}
		if val != "" {
			testsuitRecordMap[v], _ = strconv.Atoi(val)
			err = redisdb.StatisticsMatchIncr()
			if err != nil {
				return nil, nil, err
			}
		} else {
			err = redisdb.FailureMatchIncr()
			if err != nil {
				return nil, nil, err
			}
			noCacheTestSuitIds = append(noCacheTestSuitIds, v)
		}
	}
	return testsuitRecordMap, noCacheTestSuitIds, nil
}

func (c *AmountCache) GetCacheById (testsuitId string) (int, error) {
	val, err := redisdb.GetCacheById(testsuitId)
	if err != nil {
		return 0,  err
	}
	n, _ := strconv.Atoi(val)
	return n, err
}

func (c *AmountCache) SetCacheById (testsuitId string, recordNum int) error {
	_, err := redisdb.SetCacheById(testsuitId, recordNum, c.Timeout)
	return err
}

func (c *AmountCache) DeleteCacheByIds (testsuitIds []string) error {
	return redisdb.DeleteCacheByIds(testsuitIds)
}

func (c *AmountCache) GetStatisticsMatchPercentage ()  (float64, error) {
	return redisdb.GetStatisticsMatchPercentage()
}